package core;

import java.io.*;
import java.util.LinkedList;

import Index.TreeNode;
import gitobject.Commit;
import CommitLink.*;
import gitobject.Tree;
import repository.Repository;

/**
 * @author shkstart
 * @create 2021-12-02 17:03
 */
public class JitCommit {
    public static void commit(String message) throws Exception {
        Commit commit = new Commit(message);
        CommitLink commitLink = new CommitLink();
        LinkList list = commitLink.getCommitList();
        if(list.getLast() != null) {
            if (commit.getTree().equals(list.getLast().getTree())) {
                System.out.println("nothing added to commit, please check");
                return;
            }
        }
        list.insertLast(commit);
        commitLink.setCommitList(list);
        commitLink.writeObject();
        createCommit(commit);   //  在objects仓库中创建commit对象
        TreeNode temp = commit.indexTree;
        createTree(temp);   //深度遍历在objects仓库中创建当前commit对象索引树的所有Tree类对象
        commit.setLastCommit();  //
        System.out.println(commit);
    }

    public static void createCommit(Commit commit) throws IOException {
        String tree = commit.getKey();
        String commitPathDic = new File(".").getCanonicalPath() + File.separator+ ".jit" + File.separator + "objects" + File.separator + tree.substring(0,2);
        String commitPathFile = commitPathDic + File.separator + tree.substring(2, tree.length());
        File dic = new File(commitPathDic);
        dic.mkdir();
        File file = new File(commitPathFile);
        file.createNewFile();
        commit.writeObject(commitPathFile);

    }

    public static void createTree(TreeNode treeNode) throws IOException {

        String id = treeNode.getId();
        String value = new String();
        if(treeNode.getChildren() != null) {
            for (TreeNode j : treeNode.getChildren()) {
                value = j.toString() + '\n';
            }
        }
        String treeDic = new File(".").getCanonicalPath() + File.separator+ ".jit" + File.separator + "objects" + File.separator + id.substring(0,2);
        String treeFile = treeDic + File.separator + id.substring(2, id.length());
        File dic = new File(treeDic);
        dic.mkdir();
        File file = new File(treeFile);
        file.createNewFile();
        Tree tree = new Tree();
        tree.setValue(value);
        tree.setKey(id);
        tree.writeObject(treeFile);
        if(treeNode.getChildren() != null) {
            for (TreeNode tem : treeNode.getChildren()) {
                if (tem.getType().equals("tree")) {
                    createTree(tem);
                }
            }
        }
    }
}
